<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;

class WechatService
{
    /**
     * 获取不限制的小程序码
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     * 生成二维码，存到OSS，返回访问url
     * @param $page
     * @param $scene 参数
     * @param $optional
     * @return array|void
     */
    public function getUnlimitedQRCode($page, $scene = 'index', $optional = ['width' => 500, 'auto_color' => false])
    {
        $optional['page'] = trim($page, '/');
        $optional['scene'] = $scene;
        if (!isset($optional['width'])) $optional['width'] = 500;

        $api = app('easywechat.mini_app')->getClient();
        $response = $api->postJson('wxa/getwxacodeunlimit', $optional);
        $folder_name = 'wqrcode/' . str_replace('/', '_', $page);
        $filename = md5($scene) . '.png';
        $path = $folder_name . '/' . $filename;
        Storage::put($path, $response->getContent(false));
        $url = Storage::url($path);
        return $url;
    }

    //该接口用于获取小程序 scheme 码，适用于短信、邮件、外部网页、微信内等拉起小程序的业务场景。
    public function generatescheme($path, $query, $env_version)
    {
        $param = [
            'jump_wxa' => [
                'path' => $path,
                'query' => $query,
                'env_version' => $env_version
            ]
        ];
        $api = app('easywechat.mini_app')->getClient();
        $response = $api->postJson('wxa/generatescheme', $param);

        if (isset($response['errcode']) && $response['errcode'] == 0) {
            return $response['openlink'];
        } else {
            throw_invalid_request_exception('generate-scheme-fail', [], $response['errmsg']);
        }
    }
}
